package com.vcaresolution.logistic.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.springframework.stereotype.Repository;

import com.vcaresolution.logistic.form.LoginForm;
import com.vcaresolution.logistic.pojo.Securitytoken;
import com.vcaresolution.logistic.pojo.User;
import com.vcaresolution.logistic.pojo.Userbranch;
import com.vcaresolution.logistic.pojo.Userdepartment;

/**
 * The <code>UserDAO</code> class is a DAO Associated to do various 
 * options at DAO level
 *
 * @author Sneahl Shah
 * @version 1.0
 * @since ShipSoft 1.0
 */
@Repository
public class UserDAO extends BaseDAO{

	@SuppressWarnings("unchecked")
	public User login(LoginForm loginForm) {
		//TODO need to change the database call here
		System.out.println(loginForm.toString());
		
		List<User> userList = sessionFactory.getCurrentSession()
				.createCriteria(User.class)
				.add(Restrictions.eq("username", loginForm.getUsername()))
				.add(Restrictions.eq("password", loginForm.getPassword()))
				.list();
		
		
		User loggedInUser = userList.size() == 1 ? updateLastLoginDate(userList.get(0)) : null;
		
		return loggedInUser;
	}
	
	private User updateLastLoginDate(User user){
		user.setLastlogindate(new Date(System.currentTimeMillis()));
		update(user);
		
		return (User) findById(User.class, user.getUserid());
	}
	
	@SuppressWarnings("unchecked")
	public List<Userbranch> getAssociatedBranches(Serializable userId)
	{
		try
		{
			Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Userbranch.class,"userBranch");
			criteria.createAlias("userBranch.user", "user", JoinType.INNER_JOIN);
			criteria.add(Restrictions.eq("user.userid", userId));
			return criteria.list();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public List<Userdepartment> getAssociatedDepartments(Serializable userId)
	{
		try
		{
			Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Userdepartment.class,"userDepartment");
			criteria.createAlias("userDepartment.user", "user", JoinType.INNER_JOIN);
			criteria.add(Restrictions.eq("user.userid", userId));
			return criteria.list();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return null;
	}
	
	//Security Token Code - Start
	/***
	 * This method returns all the security Token for user
	 * @param userGroupId
	 * @return
	 */
	public Map<String, List<String>> populateUserTokenValues(Integer userGroupId) {
		
		Map<String, List<String>> tokenValuesMap = new HashMap<String, List<String>>();
		List<String> tokenValuesList;
		
		List<Securitytoken> listOfTokens = this.getSecurityToken(userGroupId);
		
		if(listOfTokens != null && listOfTokens.size() > 0){
			
			for(Securitytoken token : listOfTokens){
				
				String tokenname = token.getId().getTokenname();
				String tokenvalue = token.getTokenvalue();
				char mustMatch = token.getMustmatch();

				tokenValuesList = new ArrayList<String>();
				if(!tokenValuesMap.containsKey(tokenname)){
					
					if (tokenvalue != null && tokenvalue.trim().length() > 0) {
						String tokenValues[] = tokenvalue.split(";");
						
						for (int i = 0; i < tokenValues.length; i++) {
							tokenValuesList.add(tokenValues[i]);
						}
						
						tokenValuesMap.put(tokenname, tokenValuesList);
					}
					
					tokenValuesList.add("mustMatch_" + mustMatch);
					tokenValuesMap.put(tokenname, tokenValuesList);
					
				}
			}
		}
		
		return tokenValuesMap;
	}
	
	@SuppressWarnings("unchecked")
	public List<Securitytoken> getSecurityToken(Integer userGroupId) {

		try
		{
			Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Securitytoken.class,"securitytoken");
			criteria.add(Restrictions.eq("securitytoken.id.usergroupid", userGroupId));
			
			return criteria.list();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return null;
	}
	//Security Token Code - End
	
}
